#![allow(dead_code)]
fn main() {
    // basic();
    // str_insert();
    // str_join();
    // str_replace();
    // str_delete();
    // str_iter();
    // str_copy();
    str_clone();
}

// 克隆“深拷贝”,深度复制 String 中堆上的数据，而不仅仅是栈上的数据
fn str_clone(){
    let s1 = String::from("hello");
    let s2 = s1.clone();

    println!("s1 = {}, s2 = {}", s1, s2);
}
// 拷贝
fn str_copy(){
    // x 只是引用了存储在二进制中的字符串 "hello, world"，并没有持有所有权
    let x: &str = "hello, world";
    // 因此 let y = x 中，仅仅是对该引用进行了拷贝，此时 y 和 x 都引用了同一个字符串
    let y = x;
    println!("{},{}",x,y);
}
#[allow(dead_code)]
fn basic() {
    let lesson = "Go 语言微服务架构核心 22 讲";
    println!("lesson: {}", lesson);

    let mut s1 = String::new();
    s1.push_str("Hello");
    s1.push_str(" World");
    println!("s1: {}", s1);
    s1.push('_');
    s1.push('O');
    s1.push('K');
    println!("s1: {}", s1);

    let s2 = String::from("面向加薪学习");
    let result = s2.replace("学习", "努力");
    println!("result : {}", result);

    let s10 = "从0到Go语言微服务架构师";
    for c in s10.chars() {
        println!("字符：{}", c)
    }

    let s11 = "Go 语言教程 01".to_string();
    let s12 = "Go 语言教程 02".to_string();
    let result2 = s11 + " --- " + &s12;
    println!("result2: {}", result2)
}

#[allow(dead_code)]
fn str_insert() {
    let mut s = String::from("Hello World");
    s.insert(5, ',');
    s.insert_str(7, "Rust ");
    println!("{}", s);
}

#[allow(dead_code)]
fn str_join() {
    let s1 = String::from("Hello");
    let s2 = String::from("，");
    let s3 = String::from("Rust ");
    let s4 = "World";
    // let mut s = s1 + &s2 + s3.as_str() + s4;
    // s += "!";
    // println!("{}",s);

    // let mut ss = s1 + &s2 + &s3 + s4;
    // ss += "!";
    // println!("{}",ss);

    let sss = format!("{}{}{}{}{}", s1, s2, s3, s4, "!");
    println!("{}", sss)
}

#[allow(dead_code)]
fn str_replace() {
    let s = String::from("aaabbbbccaadd");
    // 表示替换所有合适的内容
    let s1 = s.replace("aa", "77");
    // replacen 表示要替换的次数，超过了也没什么问题
    let s2 = s.replacen("aa", "77", 1);
    println!("{}", s1);
    println!("{}", s2);
}

#[allow(dead_code)]
fn str_delete() {
    let mut s = String::from("Lower老虎Leopard");
    println!("{}", s.len());
    let option = s.pop(); // 返回最先 push 进入的字符，最前面的字符
    if option.is_some() {
        println!("{}", option.unwrap());
    }
    println!("{}", s.len());
    let x = s.remove(5);  // 返回索引 5 的字符，并从字符串中移除
    println!("{}", x);
    println!("{}", s.len());
    s.truncate(9);  // 从索引 9 开始至结束，全部删除
    println!("{}", s.len());
    s.clear(); // 清空字符串
    println!("{}", s.len());
}

fn str_iter() {
    let s = String::from("Lower老虎Leopard");
    let bytes = s.bytes();
    for b in bytes {
        print!("{}|",b)
    }
    println!("\n");
    let chars = s.chars();
    for c in chars {
        print!("{}|",c)
    }
}